package com.example.serverpush.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author haitao
 * @date 2021/9/3 10:44 下午
 */
@RestController
public class SseEmitterController {


    private static final Map<Long, SseEmitter> SSE_EMITTER_MAP = new HashMap<>(16);

    @GetMapping("/start/{id}")
    public SseEmitter getSseEmitter(@PathVariable Long id) {
        //0L设置永不超时
        SseEmitter sseEmitter = new SseEmitter(0L);
        SSE_EMITTER_MAP.put(id, sseEmitter);

        return sseEmitter;
    }


    //这个方法仅仅是测试，可根据业务来推送
    @GetMapping("/push/{id}")
    public void test(@PathVariable Long id) throws IOException, InterruptedException {
        //每3s向前端推送消息
        SseEmitter emitter = SSE_EMITTER_MAP.get(id);
        for (int i = 0; i < 10; i++) {
            emitter.send("后端推送信息" + i);
            Thread.sleep(3000);
        }
        emitter.complete();
    }
}
